

package com.hazelcast.internal.cluster.impl;

import com.hazelcast.cluster.Address;
import com.hazelcast.instance.impl.Node;

import java.util.concurrent.BlockingDeque;

/**
 * Listens for {@code SplitBrainJoinMessage}s and adds them for processing by split brain handler. Each message is added
 * to the head of a {@code BlockingDeque}, so that polling the {@code BlockingDeque} will return the message received last
 * (thus operating as a stack).
 */
public class SplitBrainMulticastListener implements MulticastListener {

    private final Node node;
    private final BlockingDeque<SplitBrainJoinMessage> deque;

    public SplitBrainMulticastListener(Node node, BlockingDeque<SplitBrainJoinMessage> deque) {
        this.node = node;
        this.deque = deque;
    }

    @Override
    public void onMessage(Object msg) {
        if (msg instanceof SplitBrainJoinMessage joinRequest) {
            Address thisAddress = node.getThisAddress();
            // only master nodes execute the SplitBrainHandler that processes SplitBrainJoinMessages
            if (!thisAddress.equals(joinRequest.getAddress()) && node.isMaster()) {
                deque.addFirst(joinRequest);
            }
        }
    }
}
